// src/router/index.ts
import { createRouter, createWebHashHistory } from "vue-router";
import treeList from "@/router/menuList";
import useMenuStore from "@/stores/base/menuStore";

// 是否添加了路由
let isAdd = false;

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/login.vue"),
    },
  ],
});

// 前置守卫
router.beforeEach(async (to, from) => {
  // 如果没有添加路由,此时开始添加路由
  if (!isAdd) {
    router.addRoute({
      path: "",
      redirect: "/home",
      name: "layout",
      component: () => import("@/views/layout/layout.vue"),
      children: treeList,
    });
    // 确保菜单数据已加载
    const menuStore = useMenuStore();

    try {
      // 这里需要传入router实例，但在守卫中无法直接获取
      // 建议在应用启动时就加载菜单数据
      await menuStore.fetchMenusAndRoutes(router);
    } catch (error) {
      console.error("加载菜单失败:", error);
    }

    router.addRoute(
      // 404页面路由 - 必须放在最后
      {
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: () => import("@/views/error/404.vue"),
      },
    );
    isAdd = true;

    // 重新定位, 防止动态添加路由刷新丢失情况
    return { ...to };
  }

  // 权限验证：检查目标路由是否有权限访问
  const menuStore = useMenuStore();
  const hasPermission = checkPermission(to, menuStore.getMenuList());
  // console.log("权限", hasPermission);
  // if (!hasPermission) {
  //   return { name: 'NotFound' }
  // }
});

// 检查路由权限
function checkPermission(to: any, menuList: any[]) {
  // 根路径或登录页直接允许访问
  if (to.path === "/" || to.path === "/login") {
    return true;
  }

  // 检查目标路径是否在菜单列表中
  const findRoute = (menus: any[]): boolean => {
    for (const menu of menus) {
      if (menu.path === to.path) {
        return true;
      }
      if (menu.children && findRoute(menu.children)) {
        return true;
      }
    }
    return false;
  };

  return findRoute(menuList);
}

export default router;
